//
//  AppDelegate.m
//  sensen_ios
//
//  Created by pro on 16/1/26.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "AppDelegate.h"
#import "iPN_API.h"
#import "APIs.h"
#import "WXApi.h"

#import "OrderPayRequestHandle.h"
#import "WXPayRequestHandle.h"
#import "BoyeUrlSchemeHandler.h"
#import "OrderTotalVC.h"
#import "ZKCryptionHandle.h"
#import "DeviceListVC.h"
@interface AppDelegate () <WXApiDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // 创建窗口
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.window setBackgroundColor:[UIColor blackColor]];
    [self.window makeKeyAndVisible];
    
    
    DeviceListVC *vc = (DeviceListVC *)[BoyeTool getVCWithSbIden:@"AQ" identify:@"AQ"];
    BaseNavVC *nav = [[BaseNavVC alloc] initWithRootViewController:vc];
    self.window.rootViewController = nav;
    
    // 友盟相关配置
//    [self _initUmengSocial]; // 配置友盟分享
    // 设置友盟推送
    [self _initUMessageConfig:launchOptions];
    // 配置友盟统计分析
    [self _configUMAnalytics];
    // 微信登陆配置
//    [self _weixinLoginConfig:launchOptions];
    
    [self _initGetui];
    //ipn
    [self _initIPN];
    
    return YES;
}

#pragma mark -初始化IPN

- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus{
    NSLog(@"个推收到sdk状态 %d",aStatus);
}
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId{
    NSLog(@"个推收到透传消息");
    
    //收到个推消息
    NSString *payloadMsg = nil;
    if (payloadData) {
        payloadMsg = [[NSString alloc] initWithBytes:payloadData.bytes
                                              length:payloadData.length
                                            encoding:NSUTF8StringEncoding];
    }
    
    NSString *msg = [NSString stringWithFormat:@"taskId=%@,messageId:%@,payloadMsg:%@%@",taskId,msgId, payloadMsg,offLine ? @"<离线消息>" : @""];
    NSLog(@"\n>>>[GexinSdk ReceivePayload]:%@\n\n", msg);
    
    /**
     *汇报个推自定义事件
     *actionId：用户自定义的actionid，int类型，取值90001-90999。
     *taskId：下发任务的任务ID。
     *msgId： 下发任务的消息ID。
     *返回值：BOOL，YES表示该命令已经提交，NO表示该命令未提交成功。注：该结果不代表服务器收到该条命令
     **/
//    [GeTuiSdk sendFeedbackMessage:90001 taskId:taskId msgId:msgId];
    
}
-(void) GeTuiSdkDidRegisterClient:(NSString *)clientId{
    NSLog(@"\n>>>GeTuiSdkDidRegisterClient:%@\n\n",clientId);
    
    NSString * iPN_token = [NSString stringWithFormat:@"%@",clientId];
    
    [[CacheFacade sharedCache] setObject:iPN_token forKey:@"IPN_CLIENT_ID" afterSeconds:HUGE_VALF];
    
    NSString * strDeviceToken = [[CacheFacade sharedCache] get:Device_Token];
    if(strDeviceToken != nil){
        [GeTuiSdk registerDeviceToken:strDeviceToken];
    }
}
-(void) GeTuiSdkDidOccurError:(NSError *)error{

    NSLog(@"\n>>>GeTuiSdkDidOccurError:%@\n\n",[error localizedDescription]);
}

-(void) _initGetui{
    NSLog(@"初始化个推 Start...");
    
    [GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self];
    [GeTuiSdk runBackgroundEnable:YES];
    
    [self registerRemoteNotification];
//    dispatch_sync(dispatch_queue_create(@"GETUI_QUEUE".UTF8String, DISPATCH_QUEUE_SERIAL), ^{
//        
//        
//    });
    
    NSLog(@"初始化个推 End...");
}

-(void) _initIPN{
    NSLog(@"初始化iPN start...");
    
    dispatch_async(dispatch_queue_create(@"iPN_QUEUE".UTF8String, DISPATCH_QUEUE_SERIAL), ^{
        
        INT32 ret = iPN_Initialize(IPN_INITSTRING.UTF8String, IPN_AESKEY.UTF8String);
        [DeviceCtrl getiPNErrMsg:ret];
        NSLog(@"iPN 初始化 end and ret= %d",ret);
        
    });
    NSLog(@"初始化iPN End...");
    
}


- (void)registerRemoteNotification {
    
    #ifdef __IPHONE_8_0
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        NSLog(@"UIUserNotificationTypeAlert IOS 8.0 以上");
        UIUserNotificationType types = (UIUserNotificationTypeAlert |
                                        UIUserNotificationTypeSound |
                                        UIUserNotificationTypeBadge);
        
        UIUserNotificationSettings *settings;
        settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        
    } else {
        NSLog(@"UIUserNotificationTypeAlert IOS 8.0 以下 1");
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
                                                                       UIRemoteNotificationTypeSound |
                                                                       UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    }
#else
    NSLog(@"UIUserNotificationTypeAlert IOS 8.0 以下 2");
    UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |UIRemoteNotificationTypeSound |UIRemoteNotificationTypeBadge);
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    #endif
    
}



#pragma mark - 友盟相关配置
// 友盟分享配置
- (void)_initUmengSocial{
    NSLog(@"初始化友盟配置...");
    
    [UMSocialData setAppKey:APPKEY_UMENG_SOCIAL];
    
}



// 配置友盟推送信息
- (void)_initUMessageConfig:(NSDictionary *)launchOptions {
    [UMessage startWithAppkey:APPKEY_UMENG_MESSAGE launchOptions:launchOptions];
    
//    [UMessage setLogEnabled:YES];
    
#if __IPHONE_OS_VERSION_MAaX_ALLOWED >= _IPHONE80_
    if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
    {
        //register remoteNotification types （iOS 8.0及其以上版本）
        UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier = @"action1_identifier";
        action1.title=@"Accept";
        action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序
        
        UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];  //第二按钮
        action2.identifier = @"action2_identifier";
        action2.title=@"Reject";
        action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序，在后台处理
        action2.authenticationRequired = YES;//需要解锁才能处理，如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略；
        action2.destructive = YES;
        
        UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];
        categorys.identifier = @"category1";//这组动作的唯一标示
        [categorys setActions:@[action1,action2] forContext:(UIUserNotificationActionContextDefault)];
        
        UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert
                                                                                     categories:[NSSet setWithObject:categorys]];
        [UMessage registerRemoteNotificationAndUserNotificationSettings:userSettings];
        
    }else{
        //register remoteNotification types (iOS 8.0以下)
        [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
         |UIRemoteNotificationTypeSound
         |UIRemoteNotificationTypeAlert];
    }
    
#else
    
    //register remoteNotification types (iOS 8.0以下)
    [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
     |UIRemoteNotificationTypeSound
     |UIRemoteNotificationTypeAlert];
    
#endif
}

// 配置友盟统计分析
- (void)_configUMAnalytics {
    [MobClick startWithAppkey:APPKEY_UMENG_ANALYTICS reportPolicy:BATCH   channelId:@""];
    // 版本标识
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
    
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    NSString * strDeviceToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                               stringByReplacingOccurrencesOfString: @">" withString: @""]
                              stringByReplacingOccurrencesOfString: @" " withString: @""];
    
    NSString * iPN_token = [NSString stringWithFormat:@"%@",strDeviceToken];
    
    [[CacheFacade sharedCache] setObject:iPN_token forKey:@"IPN_DEVICE_TOKEN" afterSeconds:HUGE_VALF];
    
    [[CacheFacade sharedCache] setObject:strDeviceToken forKey:Device_Token afterSeconds:HUGE_VALF];
    
    
    [GeTuiSdk registerDeviceToken:strDeviceToken];
    
    [UMessage registerDeviceToken:deviceToken];
    
    NSLog(@"didRegisterForRemoteNotificationsWithDeviceToken device_token****************:%@", strDeviceToken);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    // 此方法不要删除
    [UMessage didReceiveRemoteNotification:userInfo];
    DLog(@"接收到远程通知消息 = %@",userInfo);
//    
//    NSString * fault = [userInfo objectForKey:@"fault"];
//    if (fault != nil) {
//        //TODO: 接收到故障推送消息
//        DLog(@"fault=%@",fault);
//        return ;
//    }
}

-(void) application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    
    [GeTuiSdk resume];
    
    NSLog(@"didReceiveRemoteNotification completionHandler");
    completionHandler(UIBackgroundFetchResultNewData);
}

/* 个推-透传推送消息*/
-(void) application:(UIApplication *) application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
    
    [GeTuiSdk resume];
    
    NSLog(@"didReceiveRemoteNotification completionHandler:%@",userInfo);
    completionHandler(UIBackgroundFetchResultNewData);
}


#pragma mark -- 微信登陆配置 --
- (void)_weixinLoginConfig:(NSDictionary *)launchOptions {
    [WXApi registerApp:APPKEY_WEIXIN];
}

/*
 程序要实现和微信终端交互的具体请求与回应，因此需要实现WXApiDelegate协议的两个方法
 */
- (void)onReq:(BaseReq *)req{
    DLog(@"微信onReq");
}
- (void)onResp:(BaseResp *)resp{
    DLog(@"微信onResp");
    
    if (resp == nil) {
        NSLog(@"不能为空!");
        return;
    }
    
    // 登陆
    if([resp isKindOfClass:[SendAuthResp class]]) {
        
        SendAuthResp *temp = (SendAuthResp*)resp;
        if (temp.errCode== 0) {
            
            NSString *code = temp.code;
            NSString *state = temp.state;
            
            NSDictionary *dictionary = @{@"code":code,@"state":state};
            [[NSNotificationCenter defaultCenter] postNotificationName:@"weixinLogin" object:self userInfo:dictionary];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"weixinBind" object:self userInfo:dictionary];
        }
    }
    // 支付
    if ([resp isKindOfClass:[PayResp class]]){
        PayResp *response = (PayResp *)resp;
        switch(response.errCode){
            case
            WXSuccess:
                //服务器端查询支付通知或查询API返回的结果再提示成功
                NSLog(@"支付成功");
//                [SVProgressHUD showSuccessWithStatus:@"支付成功" withDuration:2.5];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"weixinPaySuccess" object:self userInfo:nil];
                break;
            default:
                NSLog(@"支付失败，retcode=%d", resp.errCode);
                [[NSNotificationCenter defaultCenter] postNotificationName:@"weixinPayfailure" object:self userInfo:nil];

                break;
        }
    }
}

#pragma mark - 回调
//- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
//    NSLog(@"点击的url:%@", url);
//    if ([url.host isEqualToString:@"safepay"]) {
//        //跳转支付宝钱包进行支付，处理支付结果
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"result = %@",resultDic);
//        }];
//        return YES;
//    } else {
//        return [WXApi handleOpenURL:url delegate:self]||
//        [UMSocialSnsService handleOpenURL:url]||
//        [BoyeUrlSchemeHandler handleOpenURL:url options:options];
//    }
//}
//- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
//
//    return [WXApi handleOpenURL:url delegate:self];
//
//}






#pragma mark -
- (void)applicationWillResignActive:(UIApplication *)application {
    
    // 进入后台后的操作
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [[APIs sharedInstance] close];
    
    iPN_DeInitialize();
}

@end
